<template>
  <div class="crud-opts">
    <span class="crud-opts-left">
      <!--左侧插槽-->
      <slot name="left" />
      <el-button
        v-permission="permission.publish"
        class="filter-item"
        size="mini"
        type="success"
        icon="el-icon-upload"
        :disabled="crud.selections.length !== 1 || crud.selections[0].publishState === 'PUBLISHED'"
        @click="publish(crud.selections[0])"
      >
        发布
      </el-button>
      <el-button
        v-if="crud.optShow.del"
        slot="reference"
        v-permission="permission.del"
        class="filter-item"
        type="danger"
        icon="el-icon-delete"
        size="mini"
        :loading="crud.delAllLoading"
        :disabled="crud.selections.length === 0 || isPublishing"
        @click="toDelete(crud.selections)"
      >
        删除
      </el-button>
      <slot name="right" />
    </span>
    <el-button-group class="crud-opts-right">
      <el-button
        size="mini"
        plain
        type="info"
        icon="el-icon-search"
        @click="toggleSearch()"
      />
      <el-button
        size="mini"
        icon="el-icon-refresh"
        @click="crud.refresh()"
      />
      <el-popover
        placement="bottom-end"
        width="150"
        trigger="click"
      >
        <el-button
          slot="reference"
          size="mini"
          icon="el-icon-s-grid"
        >
          <i
            class="fa fa-caret-down"
            aria-hidden="true"
          />
        </el-button>
        <el-checkbox
          v-model="allColumnsSelected"
          :indeterminate="allColumnsSelectedIndeterminate"
          @change="handleCheckAllChange"
        >
          全选
        </el-checkbox>
        <el-checkbox
          v-for="item in crud.props.tableColumns"
          :key="item.label"
          v-model="item.visible"
          @change="handleCheckedTableColumnsChange(item)"
        >
          {{ item.label }}
        </el-checkbox>
      </el-popover>
    </el-button-group>
    <el-dialog
      :close-on-click-modal="false"
      :before-close="cancelCU"
      :visible.sync="publishFlag"
      title="脚本发布"
      width="400px"
    >
      <el-form
        ref="publishForm"
        :model="publishForm"
        :rules="publishRules"
        :inline="true"
        label-width="120px"
      >
        <el-form-item
          label="发布服务器标识"
          prop="serverIds"
        >
          <el-select
            v-model="publishForm.serverIds"
            clearable
            size="small"
            placeholder="请选择发布服务器标识"
            class="filter-item"
            @change="getPublishUser"
          >
            <el-option
              v-for="item in serverLists"
              :key="item.key"
              :label="item.value"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="发布权限"
          prop="publishUser"
        >
          <el-select
            v-model="publishForm.publishUser"
            clearable
            size="small"
            placeholder="请选择发布权限"
            class="filter-item"
          >
            <el-option
              v-for="item in userList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <div
          class="dialog-footer"
          style="width:100%;text-align: center;margin-top: 20px"
        >
          <el-button @click="cancelCU">关 闭</el-button>
          <el-button
            type="primary"
            @click="publishSubmitCU"
          >发 布</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import CRUD, { crud } from '@crud/crud'
import clusterSparingApi from '@/api/cluster/clusterSparing'
import scriptPublishTaskApi from '@/api/script/publish/scriptPublishTask'
import scriptPublishVersionApi from '@/api/script/publish/scriptPublishVersion'
import roleApi from '@/api/system/role'
import userApi from '@/api/system/user'
import serverApi from '@/api/script/config/server'
import { getInfo } from '@/api/login'

export default {
  mixins: [crud()],
  props: {
    permission: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      isPublishing: false,
      publishClusterNames: '',
      publishInfo: [],
      backInfo: [],
      allColumnsSelected: true,
      allColumnsSelectedIndeterminate: false,
      publishFlag: false,
      publishForm: {
        clusterIds: [],
        serverIds: []
      },
      serverLists: [],
      userList: [],
      publishRules: {
        serverIds: [
          { required: true, message: '请选择发布服务器标识', trigger: 'blur' }
        ],
        publishUser: [
          { required: true, message: '请选择发布权限', trigger: 'blur' }
        ]
      },
      backFlag: false,
      backForm: {
        clusterIds: []
      },
      backRules: {
        clusterIds: [
          { required: true, message: '请选择还原集群', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.crud.updateProp('searchToggle', true)
    this.initData()
  },
  methods: {
    initData() {
      // 初始化获取可选择的发布服务器信息
      serverApi.findListByNoPage().then(res => {
        res.forEach((array) => {
          this.serverLists.push({key: array.id, value: array.mark, weight: array.clusterWeight})
        })
      })
    },

    getPublishUser(serverIds) {
      this.userList = []
      // 初始化获取可选择的发布用户信息
      // 集群id
      // const clusterId = this.clusterLists.filter(item => item.key === clusterIds)[0].key
      // 发布服务器id
      const serverId = this.serverLists.filter(item => item.key === serverIds)[0].key
      serverApi.findById(serverId).then((result) => {
        this.publishForm.clusterIds = result.clusterId
      })
      // 登录用户id
      var roleIdList = []
      getInfo().then((res) => {
        userApi.get(res.id).then((data) => {
          roleIdList = data
          console.log(roleIdList)
          const ids = roleIdList.join(',')

          scriptPublishVersionApi.getUserList(serverId, ids).then(res => {
            console.log(res)
            this.userList = res
          })
        })
      })
    },
    cancelCU() {
      this.publishFlag = false
      this.backFlag = false
    },
    toDelete(datas) {
      this.$confirm(`确认删除选中的${datas.length}条数据?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.crud.delAllLoading = true
        this.crud.doDelete(datas)
      }).catch(() => {
      })
    },
    publish(data) {
      this.publishInfo = data
      this.publishFlag = true
      const allServerLists = this.serverLists
      // suitableServerList适合的list需要是allServerLists中weight 小于 data.appointClusterWeight的
      this.serverLists = allServerLists.filter(item => item.weight <= data.appointClusterWeight)
    },
    back(data) {
      this.backInfo = data
      this.backFlag = true
      console.log(data.publishClusterList)
      this.backForm.clusterIds = data.publishClusterList
    },
    publishSubmitCU() {
      this.isPublishing = true
      const data = this.publishInfo
      data.publishClusterIds = this.publishForm.clusterIds.toString()
      // scriptPublishTaskApi.edit(data).then(res => {
      // })
      // 这里替换为version的发布
      scriptPublishVersionApi.publish(data, this.publishForm.serverIds, this.publishForm.clusterIds.toString(), this.publishForm.publishUser).then(info => {
        this.$notify({ title: '成功', message: '发布开始', type: 'success' })
        this.crud.refresh()
      }).finally(() => {
        this.isPublishing = false
      })

      this.publishFlag = false
    },
    backSubmitCU() {
      const publishTaskId = this.backInfo.id
      const clusterIds = this.backForm.clusterIds
      clusterIds.forEach(clusterId => {
        scriptPublishTaskApi.restore(publishTaskId, clusterId).then(info => {
          this.crud.refresh()
          this.$notify({ title: '成功', message: '还原开始', type: 'success' })
        })
      })
      this.backFlag = false
    },
    handleCheckAllChange(val) {
      if (val === false) {
        this.allColumnsSelected = true
        return
      }
      for (const key in this.crud.props.tableColumns) {
        this.crud.props.tableColumns[key].visible = val
      }
      this.allColumnsSelected = val
      this.allColumnsSelectedIndeterminate = false
    },
    handleCheckedTableColumnsChange(item) {
      let totalCount = 0
      let selectedCount = 0
      for (const key in this.crud.props.tableColumns) {
        ++totalCount
        selectedCount += this.crud.props.tableColumns[key].visible ? 1 : 0
      }
      if (selectedCount === 0) {
        this.crud.notify('请至少选择一列', CRUD.NOTIFICATION_TYPE.WARNING)
        this.$nextTick(function() {
          item.visible = true
        })
        return
      }
      this.allColumnsSelected = selectedCount === totalCount
      this.allColumnsSelectedIndeterminate = selectedCount !== totalCount && selectedCount !== 0
    },
    toggleSearch() {
      this.crud.props.searchToggle = !this.crud.props.searchToggle
    }
  }
}
</script>

<style>
.crud-opts {
  padding: 6px 0;
  display: -webkit-flex;
  display: flex;
  align-items: center;
}

.crud-opts .crud-opts-right {
  margin-left: auto;
}
</style>
